#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
 #include <fcntl.h>
 #include <sys/stat.h>
 #include <stdio.h>
using namespace std;

#define ERR_EXIT(m) \
do \
{ \
    perror(m); \
    exit(EXIT_FAILURE); \
} while(0)

#define FIFO_FILE "fifo"

class NamedPipe
{
public:
    NamedPipe(const string& path, const string& name)
        :_path(path), _name(name)
    {
        _fifo_name = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_fifo_name.c_str(), 0666);
        if(n < 0) 
        {
            ERR_EXIT("mkfifo");
        }
        cout << "fifo创建成功" << endl;
    }

    ~NamedPipe()
    {
        int n = unlink(_fifo_name.c_str());
        if(n < 0) 
        {
            ERR_EXIT("unlink");
        }
        cout << "fifo删除成功" << endl;
    }
private:
   string _path;
   string _name;
   string _fifo_name;
};

class FileOper
{
public:
    FileOper(const string& path, const string& name)
        :_path(path), _name(name), _fd(-1)
    {
        _fifo_name = _path + "/" + _name;
    }

    void OpenForRead()
    {
        _fd = open(_fifo_name.c_str(), O_RDONLY);
        if(_fd < 0) 
        {
            ERR_EXIT("open");
        }
        cout << "fifo打开成功" << endl;
    }

    void Read()
    {
        char buffer[1024];
        while(1)
        {
            int n = read(_fd, buffer, sizeof(buffer)-1);
            if(n > 0)
            {
                buffer[n] = 0;
                cout << "从client读取到的内容为:" << buffer << endl;
            }
            else if(n == 0)
            {
                cout << "读取完成" << endl;
                break;
            }
            else 
            {
                cout << "读取失败" << endl;
                break;
            }
        }
    }

    void OpenForWrite()
    {
        _fd = open(_fifo_name.c_str(), O_WRONLY); //写方式打开
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        cout << "client打开fifo成功" << endl;
    }

    void Write()
    {
        string message;
        int num = 1;
        while(true)
        {
            cout << "请输入:" << endl;
            getline(cin, message);
            message += (", message num:" + to_string(num++) + ", pid:" + to_string(getpid()));
            write(_fd, message.c_str(), message.size());
        }
    }

    void Close()
    {
        if(_fd > 0) close(_fd);
    }

    ~FileOper()
    {}
private:
   string _path;
   string _name;
   string _fifo_name;
   int _fd;
};

